package com.xsq.newmall01.ServiceImpl.SystemUserServiceImpl;

import com.xsq.newmall01.Dao.*;
import com.xsq.newmall01.Exception.ServiceException;
import com.xsq.newmall01.Mapper.SystemUserMapper;
import com.xsq.newmall01.Mapper.UserMapper;
import com.xsq.newmall01.Service.SystemUserService.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("systemService")
public class SystemServiceImpl implements SystemService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private UserMapper userMapper; // 需要注入UserMapper

    @Override
    public List<User> getAllUsers() {
        return systemUserMapper.selectAllUsers();
    }

    @Override
    public List<MerchantUser> getAllMerchants() {
        return systemUserMapper.selectAllMerchants();
    }

    @Override
    public void updateMerchantStatus(int id, int status) {
        systemUserMapper.updateMerchantStatus(id, status);
    }

    @Override
    public void updateUserStatus(int id, int status) {
        systemUserMapper.updateUserStatus(id, status);
    }

    @Override
    public List<Order> getAllOrders() {
        return systemUserMapper.selectAllOrders();
    }

    @Override
    public List<Good> getAllGoods() {
        return systemUserMapper.selectAllGoodsWithMerchant();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeGoodByAdmin(int goodId) {
        // 先删除商品，再删除所有权记录（事务保证一致性）
        systemUserMapper.deleteGoodByAdmin(goodId);
        systemUserMapper.deleteOwnershipByAdmin(goodId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recallOrder(int orderId) {
        // 1. 查询订单详情（获取商品ID和原商家ID）
        Order order = systemUserMapper.selectOrderById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 2. 删除订单
        systemUserMapper.deleteOrder(orderId);

        // 3. 将商品所有权归还原商家（senderid为原商家ID）
        systemUserMapper.updateOwnershipForRecall(order.getGoodid(), order.getSenderid());
    }

    @Override
    public SystemUser login(SystemUser systemUser) {
        return systemUserMapper.login(systemUser);
    }

    // 新增：根据ID查询普通用户
    @Override
    public User getUserById(int id) {
        return systemUserMapper.selectUserById(id);
    }

    // 新增：更新管理员信息
    @Override
    public void updateSystemUser(SystemUser systemUser) {
        systemUserMapper.updateSystemUser(systemUser);
    }

    @Override
    public void updateUserInfo(User user) {
        // 调用用户Mapper更新普通用户信息
        userMapper.updateuser(user);
    }
}
